var express = require('express');
var router = express.Router();

const sql = require("../sql/sql");
const cart = require("../sql/cart");
const pro = require("../sql/pro");
const tools = require("../tools/index");
const uuid = require("node-uuid");


/**
* @apiGroup 购物车模块
* @api {get} /api/cart 获取购物车数据
* @apiVersion 0.0.0
* @apiDescription 获取购物车数据
* @apiParam {object} userId 用户的唯一Id
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {json} data 请求数据
* @apiSuccessExample {json} Success-Response:
* {
*    "state":200,
*    "title":"请求成功",
*    "data":[{},{},{}...]
* }
* @apiSampleRequest http://localhost:3000/api/cart
*/

router.get('/',function(req,res,next){
    const { userId } = req.query;
    tools.verify(req).then(()=>{
        sql.find(cart,{userId},{_id:0,__v:0}).then(data=>{
            res.send({
                state:200,
                title:"请求购物车数据成功",
                data
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录信息已失效"
        })
    })
})

/**
* @apiGroup 购物车模块
* @api {get} /api/cart/getNum 获取购物车总数量
* @apiVersion 0.0.0
* @apiDescription 获取购物车总数量
* @apiParam {object} userId 用户的唯一Id
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {json} data 请求数据
* @apiSuccessExample {json} Success-Response:
* {
*    "state":200,
*    "title":"请求成功",
*    "data":sum
* }
* @apiSampleRequest http://localhost:3000/api/cart/getNum
*/

router.get('/getNum',function(req,res,next){
    const { userId } = req.query;
    tools.verify(req).then(()=>{
        sql.find(cart,{userId},{cartData:1,_id:0}).then(data=>{
            let sum = 0;
            let arr = data[0].cartData;
            arr.forEach(val => {
                sum += val.num
            });
            res.send({
                state:200,
                title:"请求购物总数量",
                data:sum
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录信息已失效"
        })
    })
})


/**
* @apiGroup 购物车模块
* @api {post} /api/cart/add 添加购物车
* @apiVersion 0.0.0
* @apiDescription 添加购物车
* @apiParam {object} userId 用户的唯一Id
* @apiParam {object} proId 商品的唯一Id
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {json} data 请求数据
* @apiSuccessExample {json} Success-Response:
res.send({
    state:200,
    title:"第一次添加购物车成功"
})
res.send({
    state:200,
    title:"购物车更新成功"
})
res.send({
    state:201,
    title:"商品不存在"
})
res.send({
    state:300,
    title:"登录信息已失效"
})
* @apiSampleRequest http://localhost:3000/api/cart/add
*/

router.post('/add',function(req,res,next){
    const { userId, proId } = req.body;
    tools.verify(req).then(()=>{
        sql.find(pro,{proId}).then(proData=>{
            if(proData.length > 0){
                sql.find(cart,{userId},{_id:0,__v:0}).then(data=>{
                    if(data.length <= 0){
                        sql.insert(cart,{
                            userId,
                            cartId:"cart" + uuid.v1(),
                            cartData:[{
                                proId,
                                num:1,
                                time:Date.now(),
                                flag:true
                            }]
                        })
                        res.send({
                            state:200,
                            title:"第一次添加购物车成功"
                        })
                    }else{
                        let arr = data[0].cartData;
                        let i = 0;
                        let onoff = arr.some((val,idx)=>{
                            i = idx;
                            return val.proId == proId;
                        })
                        if(onoff){
                            arr[i].num++;
                            arr[i].time=Date.now()
                        }else{
                            arr.push({
                                proId,
                                num:1,
                                flag:true,
                                time:Date.now()
                            })
                        }
                        sql.update(cart,{userId},{cartData:arr}).then(()=>{
                            res.send({
                                state:200,
                                title:"购物车更新成功"
                            })
                        })
                    }
                })
            }else{
                res.send({
                    state:201,
                    title:"商品不存在"
                })
            }
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录信息已失效"
        })
    })
})


/**
* @apiGroup 购物车模块
* @api {post} /api/cart/setNum 修改购物车数量
* @apiVersion 0.0.0
* @apiDescription 修改购物车数量
* @apiParam {object} userId 用户的唯一Id
* @apiParam {object} proId 商品的唯一Id
* @apiParam {object} num 商品数量
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {json} data 请求数据
* @apiSuccessExample {json} Success-Response:
* {
*    "state":200,
*    "title":"请求成功",
* }
* @apiSampleRequest http://localhost:3000/api/cart/setNum
*/


router.post('/setNum',function(req,res,next){
    const { userId, proId, num } = req.body;
    tools.verify(req).then(()=>{
        sql.find(cart,{userId}).then(data=>{
            let arr = data[0].cartData;
            let i = 0;
            arr.some((val,idx)=>{
                i = idx;
                return val.proId == proId;
            })
            arr[i].num = num;
            sql.update(cart,{userId},{cartData:arr}).then(()=>{
                res.send({
                    state:200,
                    title:"修改购物车数量成功"
                })
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录信息已失效"
        })
    })
})

/**
* @apiGroup 购物车模块
* @api {post} /api/cart/del 删除购物车
* @apiVersion 0.0.0
* @apiDescription 删除购物车
* @apiParam {object} userId 用户的唯一Id
* @apiParam {object} proId 商品的唯一Id
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {json} data 请求数据
* @apiSuccessExample {json} Success-Response:
* {
*    "state":200,
*    "title":"删除购物车商品成功",
* }
res.send({
    state:300,
    title:"登录信息已失效"
})
* @apiSampleRequest http://localhost:3000/api/cart/del
*/

router.post('/del',function(req,res,next){
    const { userId, proId } = req.body;
    tools.verify(req).then(()=>{
        sql.find(cart,{userId}).then(data=>{
            let arr = data[0].cartData;
            let i = 0;
            arr.some((val,idx)=>{
                i = idx;
                return val.proId == proId;
            })
            arr.splice(i,1)
            sql.update(cart,{userId},{cartData:arr}).then(()=>{
                res.send({
                    state:200,
                    title:"删除购物车商品成功"
                })
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录信息已失效"
        })
    })
})

/**
* @apiGroup 购物车
* @api {post} /api/cart/updateFlag 修改购物车选中状态
* @apiVersion 0.0.0
* @apiDescription 修改购物车选中状态
* @apiParam {String} userId 用户Id
* @apiParam {String} proId 商品Id
* @apiParam {Boolean} flag 商品选中状态
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {object} data 请求数据
* @apiSuccessExample {json} Success-Response:
res.send({
    state:200,
    title:"修改选中状态成功"
})
res.send({
    state:300,
    title:"登录信息已失效，请重新登录"
})
* @apiSampleRequest http://localhost:3000/api/cart/updateFlag
*/

// 修改购物车选中状态
router.post("/updateFlag",function(req,res,next){
    const userId = req.body.userId;
    const proId = req.body.proId;
    const flag = req.body.flag;
    tools.verify(req).then(tokenData=>{
        sql.find(cart,{userId}).then(data=>{
            let arr = data[0].cartData;
            let i = 0;
            arr.some((val,idx)=>{
                i = idx;
                return val.proId == proId;
            })
            arr[i].flag = flag;
            sql.update(cart,{userId},{cartData:arr}).then(()=>{
                res.send({
                    state:200,
                    title:"修改选中状态成功"
                })
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录信息已失效，请重新登录"
        })
    })
})


/**
* @apiGroup 购物车
* @api {post} /api/cart/updateAllFlag 修改购物车所有选中状态
* @apiVersion 0.0.0
* @apiDescription 修改购物车所有选中状态
* @apiParam {String} userId 用户Id
* @apiParam {Boolean} flag 商品选中状态
* @apiSuccess {number} state 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {object} data 请求数据
* @apiSuccessExample {json} Success-Response:
res.send({
    state:200,
    title:"修改选中状态成功"
})
res.send({
    state:300,
    title:"登录信息已失效，请重新登录"
})
* @apiSampleRequest http://localhost:3000/api/cart/updateAllFlag
*/

// 修改购物车所有选中状态
router.post("/updateAllFlag",function(req,res,next){
    const userId = req.body.userId;
    const flag = req.body.flag;
    tools.verify(req).then(tokenData=>{
        sql.find(cart,{userId}).then(data=>{
            let arr = data[0].cartData;
            for(let i = 0;i<arr.length; i++){
                arr[i].flag = flag;
            }
            sql.update(cart,{userId},{cartData:arr}).then(()=>{
                res.send({
                    state:200,
                    title:"修改所有选中状态成功"
                })
            })
        })
    }).catch(err=>{
        res.send({
            state:300,
            title:"登录信息已失效，请重新登录"
        })
    })
})



module.exports = router;
